<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple search">
            <!-- <div style="width:100px">账号信息：</div> -->
            <!-- <el-input v-model="input" placeholder="请输入菜单名称"></el-input> -->
            <i slot="label" class="el-icon-search" style="font-size:20px;margin-right:10px"></i>
            <el-select
              v-model="value"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入账号信息"
              :remote-method="remoteMethod"
              :loading="loading"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light" style="text-align:right">
            <el-button type="primary">查询</el-button>
            <el-button>重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表单 -->
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom:20px" @click="addList">添加</el-button>

      <el-table
        :data="tableData"
        :header-cell-style="{background:'#eee'}"
        border
        v-loading="loading"
        style="width: 100%;margin-bottom: 20px;"
      >
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" prop="account" label="账户"></el-table-column>
        <el-table-column align="center" prop="name" label="名称"></el-table-column>
        <el-table-column align="center" prop="role_name" label="角色名称"></el-table-column>
        <el-table-column align="center" prop="role_desc" label="角色描述"></el-table-column>
        <el-table-column align="center" prop="add_time" label="创建时间"></el-table-column>
        <el-table-column align="center" prop="last_login" label="上次登录"></el-table-column>
        <el-table-column align="center" prop="bz" label="备注"></el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleEdite(scope.row)" type="text" size="small">编辑</el-button>
            <el-button
              style="margin-left:10px"
              @click="handleReset(scope.row)"
              type="text"
              size="small"
            >重置密码</el-button>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="这是一段内容确定删除吗？"
              @onConfirm="handleDel(scope.row)"
            >
              <el-button style="margin-left:10px;color:red" slot="reference" type="text" size="small">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 右侧抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="margin-left:50px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="账户" prop="account">
          <el-input v-model="form.account" :disabled="title==='编辑'" placeholder="请输入账户"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select @focus="getRole" v-model="form.role_id" placeholder="请选择角色">
            <el-option
              v-for="item in drawSelect"
              :key="item.id"
              :label="item.role_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.bz" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelSub">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { getRoleList } from "@/api/role";
import {
  getAccountList,
  deleteAccount,
  addAccount,
  editAccount,
  resetPassword
} from "@/api/account";
import role from "../../../mock/role";
import { parseTime } from "@/utils/index";

export default {
  name: "AccountPermission",
  data() {
    return {
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      // 表数据
      tableData: [],
      // 编辑抽屉
      drawer: false,
      direction: "rtl",
      title: "编辑",
      drawSelect: [],
      //select
      options: [],
      value: [],
      list: [],
      loading: false,
      states: [],
      form: {
        name: "",
        account: "",
        role_id: "",
        bz: ""
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        account: [{ required: true, message: "请选输入账户", trigger: "blur" }],
        role_id: [{ required: true, message: "请选择角色", trigger: "blur" }]
        // bz: [{ required: true, message: "请输入备注", trigger: "blur" }]
      },
      loading: false
    };
  },
  mounted() {
    this.getAccountList();
    this.getRole();
  },
  methods: {
    // 获取账号列表
    async getAccountList() {
      this.loading = true;
      const res = await getAccountList({
        page: this.currentPage.toString(),
        limit: this.pageSize.toString(),
        keywords: ""
      });
      this.loading = false;
      this.total = res.count;
      this.tableData = res.data;

      this.tableData.forEach(item => {
        if (item.add_time == 0) {
          item.add_time = "-";
        } else {
          item.add_time = parseTime(item.add_time, "{y}-{m}-{d} {h}:{i}:{s}");
        }
        if (item.last_login == 0) {
          item.last_login = "-";
        } else {
          item.last_login = parseTime(
            item.last_login,
            "{y}-{m}-{d} {h}:{i}:{s}"
          );
        }
      });
      console.log(res);
    },
    // 获取角色
    async getRole() {
      const res = await getRoleList({
        page: this.currentPage.toString(),
        limit: "999"
      });
      this.drawSelect = res.data;
      console.log(res);
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current;
      this.getAccountList();
    },
    // select
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.list.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    // 表格操作
    addList() {
      this.title = "添加";
      this.drawer = true;
    },
    async handleDel(row) {
      console.log(row);
      const res = await deleteAccount({ id: row.id });
      console.log(res);
      if (res.st == 1) {
        this.getAccountList();
        this.$message({
          message: "删除成功",
          type: "success"
        });
      } else {
        this.$message.error("删除失败");
        console.log(error);
      }
    },
    handleEdite(row) {
      this.title = "编辑";
      const form = {
        name: row.name,
        account: row.account,
        role_id: row.role_id,
        bz: role.bz,
        id: row.id
      };
      this.form = form;
      this.drawer = true;
    },
    async handleReset(row) {
      try {
        const res = await resetPassword({ id: row.id });
        console.log(res);
        this.getAccountList();
        this.$message({
          message: "重置密码成功",
          type: "success"
        });
      } catch (error) {
        this.$message.error("重置密码失败");
        console.log(error);
      }
    },
    // 右侧抽屉
    handleClose(done) {
      this.resetForm("form");
      const form = {
        name: "",
        account: "",
        role_id: "",
        bz: ""
      };
      this.form = form;
      done();
    },
    cancelSub() {
      const form = {
        name: "",
        account: "",
        role_id: "",
        bz: ""
      };
      this.form = form;
      this.resetForm("form");
      this.drawer = false;
    },
    onSubmit() {
      console.log("submit!");
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.title === "添加") {
            const res = await addAccount({ ...this.form });
            if (res.st === 1) {
              this.resetForm("form");
              const form = {
                name: "",
                account: "",
                role_id: "",
                bz: ""
              };
              this.form = form;
              this.getAccountList();
              this.$message({
                message: "添加账户成功",
                type: "success"
              });
              this.drawer = false;
            } else {
              console.log(res);
            }
          } else if (this.title === "编辑") {
            const res = await editAccount({ ...this.form });
            if (res.st === 1) {
              this.resetForm("form");
              const form = {
                role_name: "",
                role_desc: "",
                act_list: []
              };
              this.form = form;
              this.getAccountList();
              this.$message({
                message: "编辑账户成功",
                type: "success"
              });
              this.drawer = false;
            } else {
              console.log(res);
            }
          }
        }
      });
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.drawer = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-input--medium .el-input__inner {
  width: 360px;
}
::v-deep .el-textarea__inner {
  width: 360px;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
}
</style>

